var datatable;// 定义一个全局的dataTable
var d;
var exportColumns;// 导出的列
var params;// 查询参数
$(function() {
	isGoing();
	$('#table tbody').on('click', 'tr', function() {
		if ($(this).hasClass('selected')) {
			$(this).removeClass('selected');
		} else {
			datatable.$('tr.selected').removeClass('selected');
			$(this).addClass('selected');
		}
	});

	$("#businessBigTypeId").combobox({
		select : function(event, ui) {
			loadbusinessApp();
		}
	});
	$("#businessAppId").combobox();

	$("#area").combobox();

	$("#groupId").combobox();
	$("#terminalBrandId").combobox({
		select : function(event, ui) {
			loadTerminalModel();
		}
	});
	$("#terminalModelId").combobox();
	$("#sgw").combobox();
})




function isGoing() {
	var callId = $("#callId").val();
	
	if (callId == 'call') {
		//时间维度
		var timeSizeRadio = $("#timeSizeRadio").val();
		if(timeSizeRadio){
			$("#"+timeSizeRadio).attr("checked",'checked'); 
		}
		//$("input[type=radio][name=timeSize]").eq(timeSizeRadio).attr("checked",true);
		 
		//业务维度
		var selectRadio = $("#selectRadio").val();
//		$("input[type=radio][name=radio]").eq(selectRadio).attr("checked",true);
		 $("input[type=radio][name=radio][value="+selectRadio+"]").attr("checked",true);
//		 $("input[type=radio][name=radio]").attr("checked",selectRadio);
		getRadio();
		
		var terminalBrandId = $("#terminalBrandId").val();
		if(terminalBrandId){
			loadTerminalModel();
		}
		
		var areaBoxStr_cell = $("#areaBoxStr_cell").val();
		var areaBoxStr_eNodeBID = $("#areaBoxStr_eNodeBID").val();
		if(areaBoxStr_eNodeBID){
			$("#eNodebIdBox").attr("checked",true);
		}
		if(areaBoxStr_cell){
			$("#cellBox").attr("checked",true);
		}
		getList();
	}
}

/**
 * 根据业务大类，加载业务小类
 */
function loadbusinessApp() {
	var businessBigTypeId = $("#businessBigTypeId").val();

	$
			.ajax({
				url : '../../feature/appApply/appApplyInfos?appType='
						+ businessBigTypeId,
				type : 'POST',
				dataType : 'JSON',
				error : function() {
					alert('Error loading data!');
				},
				success : function(msg) {
					$("#businessAppId").remove();
					$("#businessAppTD")
							.append(
									$("<select id='businessAppId' name='businessAppId'></select>"));
					$("#businessAppId").combobox();
					var list = msg.appList;
					$.each(eval(list), function(i, item) {
						$(
								"<option value='" + item.app_type + "'>"
										+ item.app_name + "</option>")
								.appendTo($("#businessAppId"));
					});
				}
			});

}

/**
 * 根据终端类型，加载终端型号
 * 
 * @param parentid
 */
function loadTerminalModel() {
	var terminalBrand = $("#terminalBrandId").val();

	$
			.ajax({
				url : '../../feature/terminalUE/terminalModelInfos?terminalBrand='
						+ terminalBrand,
				type : 'POST',
				dataType : 'JSON',
				error : function() {
					alert('Error loading data!');
				},
				success : function(msg) {
					$("#terminalModelId").remove();
					$("#terminalModelTD")
							.append(
									$("<select id='terminalModelId' name='terminalModelId'></select>"));
					$("#terminalModelId").combobox();
					$("#terminalModelId").append("<option value=''>全部</option>");
					var list = msg.terminalModelList;
					
					var terminalModelSelected =  $("#terminalModelSelected").val();
					if(terminalModelSelected){
						$.each(eval(list), function(i, item) {
							if(terminalModelSelected==item.terminal_model){
								$(
										"<option selected='selected' value='" + item.terminal_model + "'>"
										+ item.terminal_model + "</option>")
										.appendTo($("#terminalModelId"));
							}else{
								$(
										"<option value='" + item.terminal_model + "'>"
										+ item.terminal_model + "</option>")
										.appendTo($("#terminalModelId"));
							}
						});

					}else{
						
						$.each(eval(list), function(i, item) {
							$(
									"<option value='" + item.terminal_model + "'>"
									+ item.terminal_model + "</option>")
									.appendTo($("#terminalModelId"));
						});
					}
				}
			});

}
/**
 * 获得单选框
 */
function getRadio() {
	var selectedvalue = $("input[name='radio']:checked").val();
	for (var i = 0; i < 5; i++) {
		var tempId = '#radio_' + i;
		if (selectedvalue == i) {
			$(tempId).show();
		} else {
			$(tempId).hide();
		}
	}
}
/**
 * 页面校验
 */
function validatorParam() {
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	if (beginDate == null || beginDate == '') {
		alert("请选择开始时间");
		return false;
	}
	if (endDate == null || endDate == '') {
		alert("请选择结束时间");
		return false;
	}
	return true;
}
function getList() {
	delete d;
	var timeSize = $('input:radio[name="timeSize"]:checked').val();
	var beginDate = $("#beginDate").val();
	var endDate = $("#endDate").val();
	// 业务类型
	var businessBigTypeId = $("#businessBigTypeId").val();
	var businessAppBox = $('input:checkbox[name="businessAppBox"]:checked')
			.val();
	var businessAppId = $("#businessAppId").val();
	// 维度
	var selectRadio = $('input:radio[name="radio"]:checked').val();
	var groupId = $("#groupId").val();
	var userId = $("#userId").val();
	
	var businessBigTypeName=$('#businessBigTypeId option:selected').text();  
	var businessAppName=$('#businessAppId option:selected').text();  
	
	var terminalBrandId = $("#terminalBrandId").val();
	var terminalModelId = $("#terminalModelId").val();
	var sgw = $("#sgw").val();
	var cityCode = $("#area").val();
	if(cityCode=='全部'){
		cityCode='';
	}
	
	var tac = $("#tac").val();
	var eNodeBID = $("#eNodeBID").val();
	var areaHouse = $("#areaHouse").val();

	if (validatorParam()) {
		//$("#table tbody tr").remove();
		$("#tbodyId").remove();
		$('#table').append($("<tbody id='tbodyId'></tbody>"));
		if (datatable == undefined || datatable == "undefined"
				|| datatable == null) {
		} else {
			datatable.fnDestroy();
		}
		// 构造页面显示列
		var columns = createColumns(businessAppBox, selectRadio);

		datatable = $('#table')
				.dataTable(
						{
							"bPaginate" : true, // 翻页功能
							"bLengthChange" : false, // 改变每页显示数据数量
							"bFilter" : false, // 过滤功能
							"bSort" : true, // 排序功能
							"bInfo" : true,// 页脚信息
							"bAutoWidth" : true,// 自动宽度
							// "sPaginationType": "full_numbers",//显示分页的样式
							// 还有simple_numbers等
//							"sScrollX" : "100%",
							"sScrollXInner" : "110%",
							"iDisplayLength" : 50,
							"bScrollCollapse" : true,
							"oLanguage" : {
								"sLengthMenu" : "每页显示 _MENU_条",
								"sZeroRecords" : "没有找到符合条件的数据",
								"sProcessing" : "&nbsp;&nbsp;&nbsp;&nbsp;查询中，请稍等...",
								"sInfo" : "当前第 _START_ - _END_ 条　共计 _TOTAL_ 条",
								"sInfoEmpty" : "没有记录",
								"sInfoFiltered" : "(从 _MAX_ 条记录中过滤)",
								"sSearch" : "搜索：",
								"oPaginate" : {
									"sFirst" : "首页",
									"sPrevious" : "前一页",
									"sNext" : "后一页",
									"sLast" : "尾页"
								}
							},
							"bProcessing" : true,
							"bServerSide" : true,
							"sAjaxSource" : "../../businessAnalysis/commonBusinessPerformance/infos",
							"fnServerData" : function(sSource, aoData,
									fnCallback) {
								// 清空一次参数，保证每次查询都是最新的
								delete params;
								var areaBoxStr = "";
								$("input[name='areaBox']:checkbox").each(
										function() {
											if ($(this).attr("checked")) {
												areaBoxStr += $(this).val()
														+ "|";
											}
										});
								params = {
									"aoData" : JSON.stringify(aoData),
									"timeSize" : timeSize,
									"beginDate" : beginDate,
									"endDate" : endDate,
									"businessBigTypeId" : businessBigTypeId,
									"businessAppId" : businessAppId,
									"selectRadio" : selectRadio,
									"groupId" : groupId,
									"userId" : userId,
									"terminalBrandId" : terminalBrandId,
									"terminalModelId" : terminalModelId,
									"sgw" : sgw,
									"cityCode" : cityCode,
									"tac" : tac,
									"eNodeBID" : eNodeBID,
									"areaHouse" : areaHouse,
									"businessAppBox" : businessAppBox,
									"areaBoxStr" : areaBoxStr,
                                    "businessBigTypeName" : businessBigTypeName,
                                    "businessAppName" : businessAppName
								};
								$
										.ajax({
											"type" : "POST",
											"contentType" : "application/x-www-form-urlencoded",
											"url" : sSource,
											"dataType" : "json",
											"data" : params, // 以json格式传递
											"success" : function(resp) {
												fnCallback(resp.pageDate);
												d = resp.allData;
											}
										});
							},
							columns : columns

						});
	}
}

/**
 * 构造页面显示的列
 * 
 * @param businessAppBox
 * @param selectRadio
 */
function createColumns(businessAppBox, selectRadio) {
	var columns = [];
	exportColumns = [];
	var trObj = $('#trId');
	trObj.children().remove();
	// 时间
	trObj.append($("<th>时间</th>"));
	columns.push({
		data : "report_date"
	});
	exportColumns.push({
		"key" : "report_date",
		"name" : "时间",
		"value" : ""
	});
	// 业务大类
	trObj.append($("<th>业务大类</th>"));
	columns.push({
		data : "business_big_type_name"
	});
	exportColumns.push({
		"key" : "business_big_type_name",
		"name" : "业务大类",
		"value" : ""
	});
	// 根据页面条件显示
	// 显示服务IP
	if (businessAppBox == '0') {
		trObj.append($("<th >应用类型</th>"));
		columns.push({
			data : "business_app_name"
		});
		exportColumns.push({
			"key" : "business_app_name",
			"name" : "应用类型",
			"value" : ""
		});
	}
	// SWG
	if (selectRadio == '3') {
		trObj.append($("<th >SGW</th>"));
		columns.push({
			data : "sgw_name",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = "-";
				}
				return value;
			}
		});
		exportColumns.push({
			"key" : "sgw_name",
			"name" : "SGW",
			"value" : ""
		});
	} else if (selectRadio == '4') {// 区域
		// 城市
		trObj.append($("<th >地市</th>"));
		columns.push({
			data : "city_name"
		});
		exportColumns.push({
			"key" : "city_code",
			"name" : "地市",
			"value" : ""
		});
		// 处理areaBox多选框
		$("input[name='areaBox']:checkbox").each(function() {
			if ($(this).attr("checked")) {
				var areatBoxId = $(this).val();
				if (areatBoxId == '0') {// TAC
					trObj.append($("<th >TAC</th>"));
					columns.push({
						data : "tac"
					});
					exportColumns.push({
						"key" : "tac",
						"name" : "TAC",
						"value" : ""
					});
				} else if (areatBoxId == '1') {// eNodeBID
					trObj.append($("<th >eNodeBID</th>"));
					columns.push({
						data : "enodebid"
					});
					exportColumns.push({
						"key" : "enodebid",
						"name" : "eNodeBID",
						"value" : ""
					});
				} else if (areatBoxId == '2') {// 小区
					trObj.append($("<th >小区名称</th>"));
					columns.push({
						data : "cell_name"
					});
					exportColumns.push({
						"key" : "cell_name",
						"name" : "小区名称",
						"value" : ""
					});
				}
			}
		});
	} else if (selectRadio == '0') {// 用户组
		trObj.append($("<th >用户组</th>"));
		columns.push({
			data : "group_name",
			render : function(value, type, row) {
				if(value == null){
					value = "";
				}
				return value;
			}

		});
		// 后台需要处理
		exportColumns.push({
			"key" : "group_name",
			"name" : "用户组",
			"value" : ""
		});
	} else if (selectRadio == '1') {// 用户
		trObj.append($("<th >MSISDN</th>"));
		columns.push({
			data : "msisdn",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = "";
				}
				return value;
			}
		});
		exportColumns.push({
			"key" : "msisdn",
			"name" : "MSISDN",
			"value" : ""
		});
		trObj.append($("<th >IMSI</th>"));
		columns.push({
			data : "imsi",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = " ";
				}
				return value;
			}
		});
		exportColumns.push({
			"key" : "imsi",
			"name" : "IMSI",
			"value" : ""
		});
	} else if (selectRadio == '2') {// 终端
		trObj.append($("<th >终端类型</th>"));
//		var terminalBrandName = "";
		columns.push({
			data : "terminal_brand",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = " ";
				}
				return value;
//				$("#terminalBrandId option").each(function() {
//					if ($(this).val() == value) {
//						terminalBrandName = $(this).text();
//					}
//				});
//				return terminalBrandName;
			}
		});
		exportColumns.push({
			"key" : "terminal_brand",
			"name" : "终端类型",
			"value" : ""
		});

		var terminalModelName = "";
		trObj.append($("<th >终端型号</th>"));
		columns.push({
			data : "terminal_model",
			render : function(value, type, row) {
				if (value == null || value == "") {
					value = " ";
				}
				return value;
			}
//			render : function(value, type, row) {
//				$("#terminalModelId option").each(function() {
//					if ($(this).val() == value) {
//						terminalModelName = $(this).text();
//					}
//				});
//				return terminalModelName;
//			}
		});
		exportColumns.push({
			"key" : "terminal_model",
			"name" : "终端型号",
			"value" : ""
		});
	}
	// 用户数
	trObj.append($("<th>用户数</th>"));
	columns.push({
		data : "user_total"
	});
	exportColumns.push({
		"key" : "user_total",
		"name" : "用户数",
		"value" : ""
	});
	// 总流量
	trObj.append($("<th>总流量(Kb)</th>"));
	columns.push({
		data : "flow_total"
	});
	exportColumns.push({
		"key" : "flow_total",
		"name" : "总流量(Kb)",
		"value" : ""
	});
	// 上行包数
	trObj.append($("<th>上行包数</th>"));
	columns.push({
		data : "packet_total_up"
	});
	exportColumns.push({
		"key" : "packet_total_up",
		"name" : "上行包数",
		"value" : ""
	});
	// 下行包数
	trObj.append($("<th>下行包数</th>"));
	columns.push({
		data : "packet_total_down"
	});
	exportColumns.push({
		"key" : "packet_total_down",
		"name" : "下行包数",
		"value" : ""
	});
	// 上行流量
	trObj.append($("<th>上行流量(Kb)</th>"));
	columns.push({
		data : "flow_up"
	});
	exportColumns.push({
		"key" : "flow_up",
		"name" : "上行流量(Kb)",
		"value" : ""
	});
	// 下行流量
	trObj.append($("<th>下行流量(Kb)</th>"));
	columns.push({
		data : "flow_down"
	});
	exportColumns.push({
		"key" : "flow_down",
		"name" : "下行流量(Kb)",
		"value" : ""
	});
	// 下载速率
	trObj.append($("<th>下载速率(Kbps)</th>"));
	columns.push({
		data : "download_speed"
	});
	exportColumns.push({
		"key" : "download_speed",
		"name" : "下载速率(Kbps)",
		"value" : ""
	});

	return columns;
}

function resetQueryForm() {
	$('#queryForm')[0].reset();
	getRadio();
}

function exportExcel() {
	if (d) {
		params['exportColumns'] = JSON.stringify(exportColumns);
		$
				.ajax({
					type : "POST",
					url : "../../businessAnalysis/commonBusinessPerformance/exportBigDataExcel?rand="
							+ Math.random(),
					dataType : "json",
					"data" : params,
					success : function(data) {
						if (data.flag) {
							var url = "../../businessAnalysis/attachment/downFiles?path="
									+ data.path;
							window.location.href = url;
						} else {
							alert(data.msgs);
						}
					}
				});
	} else {
		alert("请先查询数据！");
	}
}

// 下拉树 begin
/*function onClick(e, treeId, treeNode) {
	var zTree = $.fn.zTree.getZTreeObj("treeDemo"), nodes = zTree
			.getSelectedNodes(), v = "";
	nodes.sort(function compare(a, b) {
		return a.id - b.id;
	});
	for (var i = 0, l = nodes.length; i < l; i++) {
		v += nodes[i].name + ",";
	}
	if (v.length > 0)
		v = v.substring(0, v.length - 1);
	var cityObj = $("#citySel");
	cityObj.attr("value", v);
	$("#area").val(treeNode.id);

	hideMenu();
}
*//**
 * 显示树
 *//*
function showMenu() {
	var cityObj = $("#citySel");
	var cityOffset = $("#citySel").offset();
	$("#menuContent").css({
		left : cityOffset.left - 26 + "px",
		top : cityOffset.top - 206 + "px"
	}).slideDown("fast");

	$("body").bind("mousedown", onBodyDown);
}
*//**
 * 隐藏树
 *//*
function hideMenu() {
	$("#menuContent").fadeOut("fast");
	$("body").unbind("mousedown", onBodyDown);
}
function onBodyDown(event) {
	if (!(event.target.id == "menuBtn" || event.target.id == "menuContent" || $(
			event.target).parents("#menuContent").length > 0)) {
		hideMenu();
	}
}*/